from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.select import Select

class Base:
    def __init__(self,driver):
        self.driver = driver

    def open(self,url):
        self.driver.get(url)

    def find_element(self,loc):
        try:
            WebDriverWait(self.driver,20,0.5).until(
                lambda driver:driver.find_element(*loc).is_displayed()
            )
            return self.driver.find_element(*loc)
        except Exception as e:
            print(e)

    def click(self,loc):
        self.find_element(loc).click()

    def send_keys(self,loc,info):
        self.find_element(loc).send_keys(info)

    def text(self,loc):
        return self.find_element(loc).text

    # 滚动条（执行js代码）:
    def scrollTo(self,x):
        self.driver.execute_script(f'window.scrollTo(0,{x})')

    # 弹框处理:
    def alert(self):
        self.driver.switch_to.alert.accept()

    # iframe处理:
    def iframe(self,loc):
        self.driver.switch_to.frame(self.find_element(loc))

    def iframe_content(self):
        self.driver.switch_to.default_content()

    # 切换页面:
    def new_window(self):
        self.driver.switch_to.window(self.driver.window_handles[-1])

    # 鼠标事件:
    def context(self):
        ActionChains(self.driver).context_click().perform()

    def move_to(self,m):
        ActionChains(self.driver).move_to_element(m).perform()

    def double(self):
        ActionChains(self.driver).double_click().perform()

    # 键盘事件:
    def enter(self):
        self.driver.send_keys(Keys.ENTER)

    def tab(self):
        self.driver.send_keys(Keys.TAB)

    def backspace(self):
        self.driver.send_keys(Keys.BACKSPACE)

    # 浏览器事件:
    def refresh(self):
        self.driver.refresh()

    def back(self):
        self.driver.back()

    # 下拉框选择
    def index(self,s):
        Select(self.driver).select_by_index(s)

    def value(self,s):
        Select(self.driver).select_by_value(s)

    def visible_text(self,msg):
        Select(self.driver).select_by_visible_text(msg)